<template>
  <view class="withdraw-page">


    <!-- 余额卡片 -->
    <view class="balance-card">
      <view class="balance-info">
        <text class="balance-label">可提现余额</text>
        <text class="balance-amount">¥{{ balance }}</text>
      </view>
      <view class="balance-tips">
        <text class="tips-text">最低提现金额：¥{{ config.min_amount || 10 }}</text>
      </view>
    </view>

    <!-- 快捷提现金额 -->
    <view class="quick-amounts">
      <view class="section-title">快捷金额</view>
      <view class="amounts-grid">
        <view 
          v-for="amount in quickAmounts" 
          :key="amount"
          class="amount-item"
          :class="{ active: selectedAmount === amount }"
          @click="selectAmount(amount)"
        >
          ¥{{ amount }}
        </view>
      </view>
    </view>

    <!-- 自定义金额 -->
    <view class="custom-amount">
      <view class="section-title">自定义金额</view>
      <view class="input-wrapper">
        <u-input 
          v-model="customAmount"
          type="number"
          placeholder="请输入提现金额"
          :border="true"
          @input="onAmountInput"
        />
      </view>
    </view>

    <!-- 手续费说明 -->
    <view class="fee-info" v-if="withdrawAmount > 0">
      <view class="fee-item">
        <text class="fee-label">提现金额</text>
        <text class="fee-value">¥{{ withdrawAmount }}</text>
      </view>
      <view class="fee-item">
        <text class="fee-label">手续费</text>
        <text class="fee-value">¥{{ feeAmount }}</text>
      </view>
      <view class="fee-item total">
        <text class="fee-label">实际到账</text>
        <text class="fee-value">¥{{ actualAmount }}</text>
      </view>
    </view>

    <!-- 提现按钮 -->
    <view class="withdraw-actions">
      <u-button 
        type="error" 
        :disabled="!canWithdraw"
        @click="handleWithdraw"
        :loading="loading"
      >
        立即提现
      </u-button>
    </view>

    <!-- 提现记录入口 -->
    <view class="history-entry" @click="goToHistory">
      <view class="entry-content">
        <u-icon name="clock" size="20" color="#666"></u-icon>
        <text class="entry-text">提现记录</text>
      </view>
      <u-icon name="arrow-right" size="16" color="#999"></u-icon>
    </view>

    <!-- 提现说明 -->
    <view class="withdraw-rules">
      <view class="rules-title">提现说明</view>
      <view class="rules-content">
        <text class="rule-item">• 提现金额最低{{ config.min_amount || 10 }}元，最高{{ config.max_amount || 10000 }}元</text>
        <text class="rule-item">• 每日最多可提现{{ config.daily_limit || 3 }}次</text>
        <text class="rule-item">• 工作日1-3个工作日到账，节假日顺延</text>
        <text class="rule-item">• 手续费按提现金额的{{ config.fee_rate || 0.5 }}%收取</text>
      </view>
    </view>
  </view>
</template>

<script>
import { dashboard, calculateFee, apply } from '@/api/withdraw'
import { getBalance } from '@/api/invite'

export default {
  name: 'WithdrawIndex',
  data() {
    return {
      balance: 0,
      config: {},
      selectedAmount: 0,
      customAmount: '',
      feeAmount: 0,
      loading: false,
      quickAmounts: [50, 100, 200, 500, 1000]
    }
  },
  computed: {
    withdrawAmount() {
      return this.selectedAmount || parseFloat(this.customAmount) || 0
    },
    actualAmount() {
      return Math.max(0, this.withdrawAmount - this.feeAmount)
    },
    canWithdraw() {
      const amount = this.withdrawAmount
      return amount >= (this.config.min_amount || 10) && 
             amount <= (this.config.max_amount || 10000) && 
             amount <= this.balance
    }
  },
  onLoad() {
    this.loadDashboard()
  },
  methods: {
    async loadDashboard() {
      try {
        const res = await dashboard()
        if (res.code === 0) {
          this.balance = res.data.balance || 0
          this.config = res.data.config || {}
        }
      } catch (error) {
        console.error('加载提现数据失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    },
    selectAmount(amount) {
      this.selectedAmount = amount
      this.customAmount = ''
      this.calculateWithdrawFee(amount)
    },
    onAmountInput(value) {
      this.selectedAmount = 0
      const amount = parseFloat(value) || 0
      this.calculateWithdrawFee(amount)
    },
    async calculateWithdrawFee(amount) {
      if (amount <= 0) {
        this.feeAmount = 0
        return
      }
      
      try {
        const res = await calculateFee({ amount })
        if (res.code === 0) {
          this.feeAmount = res.data.fee || 0
        }
      } catch (error) {
        console.error('计算手续费失败:', error)
      }
    },
    async handleWithdraw() {
      if (!this.canWithdraw) {
        uni.showToast({
          title: '请输入有效的提现金额',
          icon: 'none'
        })
        return
      }

      this.loading = true
      try {
        const res = await apply({
          amount: this.withdrawAmount
        })
        
        if (res.code === 0) {
          uni.showToast({
            title: '提现申请成功',
            icon: 'success'
          })
          
          // 跳转到提现详情页
          setTimeout(() => {
            uni.navigateTo({
              url: `/pages/user/withdraw/detail?id=${res.data.id}`
            })
          }, 1500)
        } else {
          uni.showToast({
            title: res.msg || '提现申请失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('提现申请失败:', error)
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    goToHistory() {
      uni.navigateTo({
        url: '/pages/user/withdraw/history'
      })
    },

  }
}
</script>

<style lang="scss" scoped>
.withdraw-page {
  min-height: 100vh;
  background-color: #f8f9fa;
}

.balance-card {
  margin: 20rpx;
  padding: 40rpx;
  background: linear-gradient(to bottom, #fe444e 0%, #fc7981 100%);
  border-radius: 20rpx;
  color: white;
  
  .balance-info {
    text-align: center;
    margin-bottom: 20rpx;
    
    .balance-label {
      display: block;
      font-size: 28rpx;
      opacity: 0.9;
      margin-bottom: 10rpx;
    }
    
    .balance-amount {
      display: block;
      font-size: 60rpx;
      font-weight: bold;
    }
  }
  
  .balance-tips {
    text-align: center;
    
    .tips-text {
      font-size: 24rpx;
      opacity: 0.8;
    }
  }
}

.quick-amounts, .custom-amount {
  margin: 20rpx;
  padding: 30rpx;
  background: white;
  border-radius: 20rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #666;
    margin-bottom: 20rpx;
  }
}

.amounts-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  
  .amount-item {
    flex: 1;
    min-width: 120rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f5f5;
    border-radius: 10rpx;
    font-size: 28rpx;
    color: #666;
    transition: all 0.3s;
    
    &.active {
      background: #fe444e;
      color: #fff;
    }
  }
}

.input-wrapper {
  margin-top: 20rpx;
}

.fee-info {
  margin: 20rpx;
  padding: 30rpx;
  background: white;
  border-radius: 20rpx;
  
  .fee-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    &.total {
      font-weight: bold;
      color: #fe444e;
    }
    
    .fee-label {
      font-size: 28rpx;
      color: #666;
    }
    
    .fee-value {
      font-size: 28rpx;
      color: #333;
    }
  }
}

.withdraw-actions {
  margin: 40rpx 20rpx;
}

.history-entry {
  margin: 20rpx;
  padding: 30rpx;
  background: white;
  border-radius: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .entry-content {
    display: flex;
    align-items: center;
    gap: 15rpx;
    
    .entry-text {
      font-size: 28rpx;
      color: #666;
    }
  }
}

.withdraw-rules {
  margin: 20rpx;
  padding: 30rpx;
  background: white;
  border-radius: 20rpx;
  
  .rules-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #666;
    margin-bottom: 20rpx;
  }
  
  .rules-content {
    .rule-item {
      display: block;
      font-size: 26rpx;
      color: #666;
      line-height: 1.6;
      margin-bottom: 10rpx;
    }
  }
}

.withdraw-primary-btn {
  background: linear-gradient(to right, #fe444e, #fc7981) !important;
  border-color: transparent !important;
  color: #ffffff !important;
  border-radius: 25rpx !important;
  font-size: 32rpx;
  font-weight: bold;
}
</style>
